

from PyQt5.QtWidgets import QWidget,QListWidgetItem,QTableWidgetItem,QHeaderView,QAbstractItemView,QSystemTrayIcon,QFrame,QShortcut

from PyQt5.QtCore import QEasingCurve,QPropertyAnimation,QRect,QTimer,QCoreApplication,Qt,QSize
from PyQt5.QtGui import QBrush,QColor,QPixmap,QIcon,QCloseEvent,QCursor,QKeySequence,QStandardItemModel,QStandardItem


import qdarkstyle

import datetime
import time
import sys
import os
import calendar

import win32gui
import win32process
import win32ui
import win32con
import win32clipboard as wcwin32 

import dataconfigui
import tableui
import mainui
import configui
import appendui
import createui
import comonyui

import asmsql
import mydef
import config
import mparts
import image


class Comony_test_gui(QWidget, comonyui.Ui_Form_test):
    def __init__(self,windwos,node):
        super(Comony_test_gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.setWindowTitle('单位/元')
        self.code = 106
        self.pushButton.clicked.connect(lambda : self.on_pushButton(0))
        self.spinBox.setMinimum(1)
        self.spinBox_4.setMinimum(1)
        self.spinBox_2.setMinimum(1990)
        datime = datetime.datetime.now()
        if node == 1:
            self.spinBox_2.setMaximum(datime.year)
            self.spinBox.setMaximum(datime.month)
            self.spinBox_4.setMaximum(datime.day)
        else:
            self.spinBox_2.setMaximum(2080)
            self.spinBox.setMaximum(12)
            self.spinBox_4.setMaximum(calendar.monthrange(datime.year,datime.month)[1])
        self.spinBox_3.setMaximum(99999)
        self.spinBox_3.setMinimum(0)
        self.spinBox.setValue(datime.month)
        self.spinBox_2.setValue(datime.year)
        self.spinBox_4.setValue(datime.day)
        self.spinBox.valueChanged.connect(self.on_spinbox)
        self.spinBox_2.valueChanged.connect(self.on_spinbox)
        if node == 2:
            self.spinBox.setEnabled(False)
            self.spinBox_2.setEnabled(False)
            self.spinBox_4.setEnabled(False)
	
    def on_pushButton(self,event):
        self.windwos.windwos.qthead.mycall(self.spinBox_2.value(),self.spinBox.value(),self.spinBox_4.value(),self.spinBox_3.value(),'add', self.code)
        self.close()

    def on_spinbox(self):
        cur = calendar.monthrange(self.spinBox_2.value(),self.spinBox.value())
        self.spinBox_4.setMaximum(cur[1])
        self.spinBox_4.setValue(cur[1])


class Comony_Gui(QWidget, comonyui.Ui_Form):
    def __init__(self,windwos):
        super(Comony_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.resize(700, 360)
        self.setWindowTitle('进货记账本')
        self.spinBox.setMaximum(12)
        self.spinBox.setMinimum(1)
        self.spinBox.setValue(datetime.datetime.now().month)
        self.spinBox_2.setMaximum(2080)
        self.spinBox_2.setMinimum(1990)
        self.spinBox_2.setValue(datetime.datetime.now().year)
        self.model=QStandardItemModel(5,7)
        self.model.setHorizontalHeaderLabels(['星期一','星期二','星期三','星期四',"星期五","星期六","星期日"])
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.setEnabled(False)
        self.tableView.verticalHeader().setVisible(False)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(0))
        self.pushButton_2.clicked.connect(lambda : self.on_pushButton(1))
        self.spinBox.valueChanged.connect(self.on_spinbox)
        self.spinBox_2.valueChanged.connect(self.on_spinbox)
        self.code = 106
        self.windwos.qthead.Dic_Signal.connect(self.mevent)
        self.on_getdata()
        self.on_spinbox()		

    def mevent(self,dic):
        if self.code == dic['code']:
            if dic['mode'] == "add":
                if dic['ret'][0] == self.spinBox_2.value() and dic['ret'][1] == self.spinBox.value():
                    row,cor = self.on_get_cur(dic['ret'][2])
                    self.model.setItem(row,cor,QStandardItem(str(dic['ret'][2]) + "  [" + str(dic['ret'][3]) + "元]"))
            elif dic['mode'] == "see":
                row,cor = self.on_get_cur(dic['ret'][3])
                self.model.setItem(row,cor,QStandardItem(str(dic['ret'][3]) + "  [" + str(dic['ret'][4]) + "元]"))
            elif dic['mode'] == "set":
                self.label.setText(dic['ret']+"元")
            #print(dic)

    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)

    def on_getdata(self):          
        self.windwos.qthead.mycall(self.spinBox_2.value(),self.spinBox.value(),'see', self.code)

    def on_get_cur(self,day):
        r = 0
        for v in range(5):
            for z in range(7):
                r += 1
                if r >= day:
                    return v,z

    def on_spinbox(self):
        r = 0
        cur = calendar.monthrange(self.spinBox_2.value(),self.spinBox.value())		
        for row in range(5):
            for cor in range(7):
                if r > cur[1]-1:
                    self.model.setItem(row,cor,QStandardItem(""))
                else:
                    r += 1
                    self.model.setItem(row,cor,QStandardItem(str(r)))
        self.on_getdata()					
        #self.tableView.setModel(self.model)

    def on_pushButton(self,event):
        if event == 0:
            win = Comony_test_gui(self,1)
            win.show()
        elif event == 1:
            win = Comony_test_gui(self,2)
            win.show()



class Createui_Gui(QWidget, createui.Ui_Form):
    def __init__(self,windwos):
        super(Createui_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(0))
        self.lineEdit_3.setPlaceholderText("12")
        self.setWindowTitle('自定义创建商品')
        self.lineEdit_3.setText("12")
        self.lineEdit_4.setText("0")
        self.lineEdit_5.setText("0")
        self.code = 105
        self.windwos.qthead.Dic_Signal.connect(self.mevent)

    def mevent(self,dic):
        if self.code == dic['code']:
            print(dic)
            self.lineEdit.setText("")
            self.lineEdit_6.setText("")
            self.lineEdit_2.setText("")
            self.lineEdit_3.setText("12")
            self.lineEdit_4.setText("0")
            self.lineEdit_5.setText("0")

    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)

    def on_pushButton(self,mint):
        mid   = self.lineEdit.text()
        name  = self.lineEdit_6.text()
        note  = self.lineEdit_2.text()
        mtime = self.lineEdit_3.text()
        meony = self.lineEdit_4.text()
        msum  = self.lineEdit_5.text()
        try:
            int(mid)
        except ValueError:
            mparts.My_QMessageBox("添加失败","编码非法字符",self).exec_()
            return
        try:
            int(mtime)
        except ValueError:
            mparts.My_QMessageBox("添加失败","保质期非法字符",self).exec_()
            return
        try:
            msum  = int(msum)
            meony = float(meony)
        except:
            msum  = '0'
            meony = '0'
        self.windwos.qthead.mycall(mid,name,note,mtime,meony,msum,'add', self.code)



class Dataconfigui_Gui(QWidget, dataconfigui.Ui_Form):
    def __init__(self,windwos):
        super(Dataconfigui_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.pushButton_3.clicked.connect(lambda : self.on_pushButton(0))
        self.pushButton_2.clicked.connect(lambda : self.on_pushButton(1))
        self.pushButton.clicked.connect(lambda : self.on_pushButton(2))
        self.lineEdit.returnPressed.connect(lambda : self.on_lineEdit(0))
        #self.lineEdit_7.clicked.connect(lambda: self.on_menu(1))
        self.listWidget.itemSelectionChanged.connect(lambda : self.on_pushButton(3))
        self.lineEdit_4.setPlaceholderText("12")
        self.listWidget.setDragDropMode(QAbstractItemView.InternalMove)
        self.setWindowTitle('编码库')
        self.mmenu = mparts.menu(self, self.windwos,["复制"], self.on_menu)

        self.lineEdit_7.setEnabled(False)
        self.lineEdit_6.setEnabled(False)
        self.setCursor(QCursor(self.windwos.icon))
        self.code = 104

        self.widget = mparts.popup()

        self.windwos.qthead.Dic_Signal.connect(self.mevent)
        self.windwos.qthead.mycall('add', self.code)

    def mevent(self,dic):
        if self.code == dic['code']:
            print(dic)
            if dic['mode'] == "add":
                item = QListWidgetItem()
                item.setText(str(dic['ret'][0]))
                self.listWidget.addItem(item)

            elif dic['mode'] == "see":
                self.widget._stop()
                if len(dic['ret'][0]) > 2:
                    self.lineEdit_7.setText(str(dic['ret'][0][0]))
                    self.lineEdit_6.setText(dic['ret'][0][1])
                    self.lineEdit_5.setText(dic['ret'][0][2])
                    self.lineEdit_4.setText(dic['ret'][0][3])
                    self.lineEdit_3.setText(str(dic['ret'][0][4]))
                    self.lineEdit_2.setText(str(dic['ret'][0][5]))
                else:
                    mparts.My_QMessageBox("查找提示","查找失败，数据未入库",self).exec_()
                    mid = self.listWidget.currentRow()
                    if mid != -1:
                        if dic['ret'][1] == self.listWidget.item(mid).text():
                            self.listWidget.takeItem(mid)

            elif dic['mode'] == "set":
                self.widget._stop()
                #mparts.My_QMessageBox("修改提示","修改完成",self).exec_()

            elif dic['mode'] == 'del':
                self.widget._stop()
                #mparts.My_QMessageBox("删除提示","删除完成",self).exec_()
                mid = self.listWidget.currentRow()
                if mid != -1:
                    if dic['ret'] == self.listWidget.item(mid).text():
                        self.listWidget.takeItem(mid)

            elif dic['mode'] == 'icon':
                self.setCursor(QCursor(self.windwos.icon))

    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)

    def paintEvent(self, event):
        super(Dataconfigui_Gui, self).paintEvent(event)
        self.widget._update(self.size(), self.x(), self.y())

    def contextMenuEvent(self, event):
        x   = event.pos().x()
        y   = event.pos().y()
        pos = self.lineEdit_7.pos()
        mx  = (pos.x(), pos.x() + self.lineEdit_7.size().width())
        my  = (pos.y(), pos.y() + self.lineEdit_7.size().height())
        if x > mx[0] and x < mx[1] and y > my[0] and y < my[1]:
            self.mmenu.exec_(event.globalPos())

    def on_pushButton(self,mint):
        mid = self.lineEdit.text()
        if mint == 0:
            try:
                int(mid)
            except ValueError:
                mparts.My_QMessageBox("查找提示","查找失败，格式有误",self).exec_()
                return
            self.widget._start(self.x(), self.y())    
            self.windwos.qthead.mycall(mid,'see',self.code)

        elif mint == 1:
            mid    = self.lineEdit_7.text()
            note   = self.lineEdit_5.text()
            mtime  = self.lineEdit_4.text()
            try:
                mmoney = float(self.lineEdit_3.text())
                msum   = int(self.lineEdit_2.text())
            except:
                mmoney = "0"
                msum   = "0"
            try:
                mtime  = int(self.lineEdit_4.text())
            except:
                mparts.My_QMessageBox("修改提示","保质期必须是数字",self).exec_()
                return     
            #mid = mid[:mid.find(" ")]
            self.widget._start(self.x(), self.y())
            self.windwos.qthead.mycall(note,mtime,mmoney,msum,mid,'set',self.code)

        elif mint == 2:
            mid    = self.lineEdit_7.text()
            mbox = mparts.MessageBox(self, text='确认删除吗？', count=3, title="删除提示")
            mbox.exec_()
            if mbox.clickedButton() == mbox.closeBtn0:
                #mid = mid[:mid.find(" ")]
                self.widget._start(self.x(), self.y())
                self.windwos.qthead.mycall(mid, 'del', self.code)

        elif mint == 3:
            mid = self.listWidget.currentRow()
            if mid != -1:
                mid = self.listWidget.item(mid).text()
                self.widget._start(self.x(), self.y())
                self.windwos.qthead.mycall(mid, 'see', self.code)


    def on_lineEdit(self,mint):
        if mint == 0:
            mid = self.lineEdit.text()
            try:
                int(mid)
            except ValueError:
                mparts.My_QMessageBox("查找提示","查找失败，格式有误",self).exec_()
                return
            self.widget._start(self.x(), self.y())    
            self.windwos.qthead.mycall(mid, 'see', self.code)
        elif mint == 1:
            self.mmenu.exec_()

    def on_menu(self,mint):
        wcwin32.OpenClipboard()  
        wcwin32.EmptyClipboard()  
        wcwin32.SetClipboardData(win32con.CF_UNICODETEXT, self.lineEdit_7.text())  
        wcwin32.CloseClipboard()  



class mTableui(QWidget, tableui.Ui_Forms):
    def __init__(self,windwos,title,mod,*data):
        super(mTableui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.setWindowTitle(title)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableWidget.verticalHeader().setVisible(False)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(mod,*data))
        self.code = 1011
        self.mylamd = lambda dic, mod=mod: self.mevent(dic,mod)
        self.windwos.qthead.Dic_Signal.connect(self.mylamd)
        if mod:
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.windwos.qthead.mycall('0', data[-1], 'see', self.code)
        else:
            self.windwos.qthead.mycall(data[0], 'set', self.code)

    def closeEvent(self, event):
        self.windwos.qthead.Dic_Signal.disconnect(self.mylamd)
        self.destroy()

    def mevent(self,dic,mod):
        if self.code == dic['code']:
            print(dic)
            if dic['mode'] == 'add':
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                item0 = QTableWidgetItem(str(dic['ret'][0]))
                item1 = QTableWidgetItem(str(dic['ret'][8]))
                item4 = QTableWidgetItem(dic['ret'][3])
                item6 = QTableWidgetItem(dic['ret'][9])
                if not mod:
                    item0.setFlags(Qt.ItemFlag.ItemIsEnabled)
                    item1.setFlags(Qt.ItemFlag.ItemIsEnabled)
                    item4.setFlags(Qt.ItemFlag.ItemIsEnabled)
                    item6.setFlags(Qt.ItemFlag.ItemIsEnabled)
                self.tableWidget.setItem(row,0, item0)
                self.tableWidget.setItem(row,1, item1)
                self.tableWidget.setItem(row,2, QTableWidgetItem(dic['ret'][1]))
                self.tableWidget.setItem(row,3, QTableWidgetItem(dic['ret'][2]))
                self.tableWidget.setItem(row,4, item4)
                self.tableWidget.setItem(row,5, QTableWidgetItem(dic['ret'][5]))
                self.tableWidget.setItem(row,6, item6)
                self.tableWidget.setItem(row,7, QTableWidgetItem(str(dic['ret'][6])))
                self.tableWidget.setItem(row,8, QTableWidgetItem(str(dic['ret'][7])))

            elif dic['mode'] == 'close':
                self.pushButton.click()

    def on_pushButton(self,mod,*data):
        if mod == True:
            tables = self.tableWidget.selectedItems()
            for k,v in enumerate(tables):
                index = k*9
                if index+1 > len(tables):
                    break
                _id = tables[index].text()    
                self.windwos.qthead.mycall(_id, str(_id), "1", 'set', 103)
            self.windwos.qthead.mycall(*data, 'add', 101)
        else:
            if self.tableWidget.item(0,0):
                _id        = self.tableWidget.item(0,0).text()
                _stat_time = self.tableWidget.item(0,2).text()
                _stop_time = self.tableWidget.item(0,3).text()
                _note      = self.tableWidget.item(0,5).text()
                _meony     = self.tableWidget.item(0,7).text()
                _sum       = self.tableWidget.item(0,8).text()
                mtime  = mydef.getmtime(_stat_time, _stop_time)
                if not mtime[0]:
                    mparts.My_QMessageBox("修改提示","修改失败，{}".format(mtime[1]),self).exec_()
                    return 
                self.windwos.qthead.mycall(_stat_time,_stop_time,_note,_meony,_sum,_id,data[1],'update', 103)
        self.close()



class Tableui_Gui(QWidget, tableui.Ui_Form):
    def __init__(self,windwos):
        super(Tableui_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(0))
        self.pushButton_2.clicked.connect(lambda : self.on_pushButton(1))
        self.setWindowTitle('信息表')
        self.windwos.qthead.Dic_Signal.connect(self.mevent)
        self.code = 103
        self.mmenu = mparts.menu(self, self.windwos,("修改","删除","移至过期"),self.on_menu)
        self.mmenu2 = mparts.menu(self, self.windwos,["恢复","删除"],self.on_menu)
        self._animation = QPropertyAnimation(self.mmenu, b'geometry', self, easingCurve=QEasingCurve.Linear, duration=300)
        self._animation1 = QPropertyAnimation(self.mmenu2, b'geometry', self, easingCurve=QEasingCurve.Linear, duration=300)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.verticalHeader().setVisible(False)
        self.setCursor(QCursor(self.windwos.icon))

        self.pushButton.setEnabled(False) 
        self.pushButton_2.setEnabled(True)

        self.widget = mparts.popup()

        self.windwos.qthead.mycall('0', 'add', self.code)

    def mevent(self,dic):
        if self.code == dic['code']:
            print(dic)
            if dic['mode'] == "add":
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                item0 = QTableWidgetItem(str(dic['ret'][8]))
                item1 = QTableWidgetItem(str(dic['ret'][9]))
                item2 = QTableWidgetItem(str(dic['ret'][3]))
                item3 = QTableWidgetItem(str(dic['ret'][5]))
                item4 = QTableWidgetItem(str(dic['ret'][6]))
                item5 = QTableWidgetItem(str(dic['ret'][7]))
                item7 = QTableWidgetItem(str(dic['ret'][0]))
                if not self.pushButton.isEnabled():
                    mday = datetime.datetime.strptime(dic['ret'][2], "%Y-%m-%d") - datetime.datetime.now()
                    if mday.days < 0:
                        item6 = QTableWidgetItem("已过期{}天".format(abs(mday.days)))
                    else:
                        item6 = QTableWidgetItem("{}天".format(mday.days))
                    if mday.days < config.Myconfig._mdays:
                        item6.setForeground(QBrush(QColor(255,0,0)))
                    else:
                        item6.setForeground(QBrush(QColor(0,255,0)))
                else:
                    item6 = QTableWidgetItem(dic['ret'][2])
                    item0.setForeground(QBrush(QColor(128,138,135)))
                    item1.setForeground(QBrush(QColor(128,138,135)))
                    item2.setForeground(QBrush(QColor(128,138,135)))
                    item3.setForeground(QBrush(QColor(128,138,135)))
                    item4.setForeground(QBrush(QColor(128,138,135)))
                    item5.setForeground(QBrush(QColor(128,138,135)))
                    item6.setForeground(QBrush(QColor(128,138,135)))
                    item7.setForeground(QBrush(QColor(128,138,135)))
                self.tableWidget.setItem(row,0, item0)
                self.tableWidget.setItem(row,1, item1)
                self.tableWidget.setItem(row,2, item2)
                self.tableWidget.setItem(row,3, item3)
                self.tableWidget.setItem(row,4, item4)
                self.tableWidget.setItem(row,5, item5)
                self.tableWidget.setItem(row,6, item6)
                self.tableWidget.setItem(row,7, item7)

            elif dic['mode'] == 'set':
                if dic['ret']:
                    self.tableWidget.item(dic['ret'][6],3).setText(dic['ret'][2])
                    self.tableWidget.item(dic['ret'][6],4).setText(str(dic['ret'][3]))
                    self.tableWidget.item(dic['ret'][6],5).setText(str(dic['ret'][4]))
                    mday = datetime.datetime.strptime(dic['ret'][1], "%Y-%m-%d") - datetime.datetime.now()
                    if mday.days < 0:
                        self.tableWidget.item(dic['ret'][6],6).setText("已过期{}天".format(abs(mday.days)))
                    else:
                        self.tableWidget.item(dic['ret'][6],6).setText("{}天".format(mday.days))
                    if mday.days < config.Myconfig._mdays:
                        self.tableWidget.item(dic['ret'][6],6).setForeground(QBrush(QColor(255,0,0)))
                    else:
                        self.tableWidget.item(dic['ret'][6],6).setForeground(QBrush(QColor(0,255,0)))
                    #self.tableWidget.item(dic['ret'][7],6).setText()               
                    #mparts.My_QMessageBox("修改提示","修改完成",self).exec_()
                    #else:
                    #mparts.My_QMessageBox("修改提示","修改失败",self).exec_()

            elif dic['mode'] == 'del':
                if type(dic['ret']) == int:
                    self.tableWidget.removeRow(dic['ret'])
                elif type(dic['ret']) == str:
                    items = self.tableWidget.findItems(dic['ret'],Qt.MatchExactly)
                    for v in items:
                        if self.tableWidget.item(v.row(),7).text() == dic['ret']:
                            self.tableWidget.removeRow(v.row())
                            break
            elif dic['mode'] == 'addm':
                if not self.pushButton.isEnabled():
                    dic.update({'mode':'add'})
                    self.mevent(dic)
            elif dic['mode'] == 'stop':
                self.tableWidget.sortItems(6,Qt.DescendingOrder) #DescendingOrder AscendingOrder
                self.widget._stop()

            elif dic['mode'] == 'icon':
                self.setCursor(QCursor(self.windwos.icon))

    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)
        
    def paintEvent(self, event):
        super(Tableui_Gui, self).paintEvent(event)
        self.widget._update(self.size(), self.x(), self.y())

    def on_menu(self,mint):
        if mint == 0:
            if not self.pushButton.isEnabled():
                c = "修改"
            else:
                c = "恢复"
        elif mint == 1:
            c = "删除"
        elif mint == 2:
            c = "移至过期"
        mbox = mparts.MessageBox(self, text='确认{}吗？'.format(c), count=3, title="{}提示".format(c))
        mbox.exec_()
        if mbox.clickedButton() == mbox.closeBtn0:
            sid = self.tableWidget.currentRow()
            mid = self.tableWidget.item(sid,7).text()
            if c == "修改":
                web = mTableui(self.windwos,'点击修改',False,mid,sid)
                web.show()
            elif c == "删除":
                self.windwos.qthead.mycall(mid,sid, 'del', self.code)
            elif c == "移至过期":
                self.windwos.qthead.mycall(mid,sid, "1", 'set', self.code)
            elif c == "恢复":
                self.windwos.qthead.mycall(mid,sid, "0", 'set', self.code)

    def contextMenuEvent(self, event):
        if self.tableWidget.selectedItems():
            pos  = event.globalPos()
            if not self.pushButton.isEnabled():
                size = self.mmenu.sizeHint()
                self._animation.stop()
                self._animation.setStartValue(QRect(pos.x(), pos.y(), 0, 0))
                self._animation.setEndValue(QRect(pos.x(), pos.y(), size.width(), size.height()))
                self._animation.start()
                self.mmenu.exec_(event.globalPos())
            else:
                size = self.mmenu2.sizeHint()
                self._animation1.stop()
                self._animation1.setStartValue(QRect(pos.x(), pos.y(), 0, 0))
                self._animation1.setEndValue(QRect(pos.x(), pos.y(), size.width(), size.height()))
                self._animation1.start()
                self.mmenu2.exec_(event.globalPos())

    def on_pushButton(self,mint):
        while self.tableWidget.rowCount():
            self.tableWidget.removeRow(0)
        self.widget._start(self.x(), self.y())    
        if mint == 0:
            self.pushButton.setEnabled(False) 
            self.pushButton_2.setEnabled(True)
            self.windwos.qthead.mycall('0', 'add', self.code)
        elif mint == 1:
            self.pushButton.setEnabled(True) 
            self.pushButton_2.setEnabled(False)
            self.windwos.qthead.mycall('1', 'add', self.code)



class Appendui_Gui(QWidget, appendui.Ui_Form):
    def __init__(self,windwos):
        super(Appendui_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(0))
        #self.lineEdit_6.editingFinished.connect(lambda : self.on_lineEdit(0))
        self.lineEdit_6.returnPressed.connect(lambda : self.on_lineEdit(0))
        self.lineEdit_4.returnPressed.connect(lambda : self.on_lineEdit(1))
        self.lineEdit_7.returnPressed.connect(lambda : self.on_lineEdit(1))
        self.lineEdit_7.setPlaceholderText(time.strftime("%Y-%m-%d"))
        self.lineEdit_4.setPlaceholderText(time.strftime("%Y-%m-%d"))
        #self.lineEdit_5.textChanged.connect(lambda : self.on_lineEdit(1))
        #self.lineEdit.textChanged.connect(lambda : self.on_lineEdit(2))
        #self.lineEdit_4.textChanged.connect(lambda : self.on_lineEdit(3))
        #self.lineEdit_3.textChanged.connect(lambda : self.on_lineEdit(4))
        #self.lineEdit_2.textChanged.connect(lambda : self.on_lineEdit(5))
        self.setWindowTitle('添加')
        self.setCursor(QCursor(self.windwos.icon))
        self.widget = mparts.popup()
        self.windwos.qthead.Dic_Signal.connect(self.mevent)
        self.code = 101

    def mevent(self,dic):
        if self.code == dic['code']:
            print(dic)
            if dic['mode'] == 'add':
                self.widget._stop()
                mparts.My_QMessageBox("添加提示",dic['ret'],self).exec_()

            elif dic['mode'] == 'see':
                self.widget._stop()
                self.lineEdit_5.setText(dic['ret'][0][1])
                if len(dic['ret'][0]) > 3:
                    if config.Myconfig._write == 1:
                        self.lineEdit.setText(dic['ret'][0][2])
                        self.lineEdit_4.setText(dic['ret'][0][3])
                        self.lineEdit_2.setText(str(dic['ret'][0][5]))
                        self.lineEdit_3.setText(str(dic['ret'][0][4]))
                    if config.Myconfig._cargo == 1:
                        self.on_pushButton(1)

            elif dic['mode'] == 'icon':
                self.setCursor(QCursor(self.windwos.icon))

    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)

    def paintEvent(self, event):
        super(Appendui_Gui, self).paintEvent(event)
        self.widget._update(self.size(), self.x(), self.y())

    def on_pushButton(self,mint):
        mid    = self.lineEdit_6.text()
        note   = self.lineEdit.text()
        name   = self.lineEdit_5.text()
        m_stat, m_stop  = mydef.getmtime(self.lineEdit_7.text(), self.lineEdit_4.text())
        try:
            int(mid)
        except ValueError:
            mparts.My_QMessageBox("添加提示","添加失败，商品编码错误",self).exec_()
            return 
        if not m_stat:
            mparts.My_QMessageBox("添加提示","添加失败，{}".format(m_stop),self).exec_()
            return 
        self.lineEdit_7.setText(m_stat)
        self.lineEdit_4.setText(m_stop)
        try:
            msum   = int(self.lineEdit_2.text())
            mmoney = float(self.lineEdit_3.text())
        except:
            msum   = '0'
            mmoney = '0'
        if config.Myconfig._synch:
            day = datetime.datetime.strptime(m_stop, "%Y-%m-%d") - datetime.datetime.strptime(m_stat, "%Y-%m-%d")
            mtime = day.days//30
            self.windwos.qthead.mycall(note,mtime,mmoney,msum,mid,'set',104)
        if mint == 1 or config.Myconfig._cargo == 1:
            self.widget._start(self.x(), self.y())
            self.windwos.qthead.mycall(m_stat, m_stop, note, mmoney, msum, name, mid, 'pyqt', 'add', self.code)
        else:
            web = mTableui(self.windwos, '选中替换', True, m_stat, m_stop, note, mmoney, msum, name, mid)
            web.show()

    def on_lineEdit(self,mint):
        if mint == 0:
            mid = self.lineEdit_6.text()
            try:
                int(mid)
            except ValueError:
                mparts.My_QMessageBox("添加提示","添加失败，商品编码错误",self).exec_()
                return
            self.widget._start(self.x(), self.y())    
            self.windwos.qthead.mycall(mid, 'see', self.code)
        elif mint == 1:
            mtime  = mydef.getmtime(self.lineEdit_7.text(), self.lineEdit_4.text())
            if not mtime[0]:
                mparts.My_QMessageBox("添加提示","添加失败，{}".format(mtime[1]),self).exec_()
            else:
                self.lineEdit_7.setText(mtime[0])
                self.lineEdit_4.setText(mtime[1])



class Mainui_Gui(QWidget, mainui.Ui_Form):
    def __init__(self):
        super(Mainui_Gui, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(lambda : self.on_pushButton(Appendui_Gui))
        self.pushButton_3.clicked.connect(lambda : self.on_pushButton(Tableui_Gui))
        self.pushButton_2.clicked.connect(lambda : self.on_pushButton(Configui_Gui))
        self.pushButton_4.clicked.connect(lambda : self.on_pushButton(Dataconfigui_Gui))
        self.pushButton_5.clicked.connect(lambda : self.on_pushButton(Comony_Gui))
        self.pushButton_6.clicked.connect(lambda : self.on_pushButton(Createui_Gui))
        short = QShortcut(QKeySequence("Ctrl+T"),self)
        short.activated.connect(lambda : self.on_pushButton(Createui_Gui))
        self.setWindowTitle('主页面')
        self.icon = QPixmap()
        self.icon.loadFromData(image.img[config.Myconfig._theme])
        self.setCursor(QCursor(self.icon))
        tray = QSystemTrayIcon(self)
        qpmp = QPixmap()
        qpmp.loadFromData(image.zhu)
        tray.setIcon(QIcon(qpmp))
        mmenu = mparts.menu(self, self,("打开","退出"), self.on_menu)
        tray.messageClicked.connect(lambda : self.on_menu(3))
        tray.activated.connect(lambda reason: self.on_menu(reason+1))
        tray.setContextMenu(mmenu)
        tray.setToolTip("小托盘")
        tray.show()
        self.qthead = mydef.pyqt_thread()
        self.qthead.start()
        self.qthead.my_call(mydef.main_init)
        self._timer = QTimer(self, timeout=lambda : self.mupdate(Tableui_Gui))
        self._timer.setInterval(3600000)
        #self._timer.setInterval(12000)
        self._timer.start()

    def mupdate(self,name):
        if hasattr(self, name.__name__):
            mclass = getattr(self, name.__name__)
            while mclass.tableWidget.rowCount():
                mclass.tableWidget.removeRow(0)
            if mclass.pushButton.isEnabled():
                mclass.pushButton.setEnabled(False) 
                mclass.pushButton_2.setEnabled(True)
            self.qthead.mycall('0', 'add', 103)
        else:
            print("None object")

    def myclose(self, name, call):
        mclass = getattr(self, name) 
        self.qthead.Dic_Signal.disconnect(call)
        mclass.destroy()
        delattr(self, name)

    def isrung(self,data):
        self.on_menu(3)

    def closeEvent(self, event):
        if event.spontaneous():
            self.hide()
            event.ignore()
        else:
            mbox = mparts.MessageBox(self, text='确认退出吗？', count=2, title="退出提示")
            mbox.exec_()
            if mbox.clickedButton() == mbox.closeBtn0:
                self.qthead._stop()
                self._timer.stop()
                sys.exit()
            else:
                event.ignore()

    def on_menu(self,mint):
        if mint == 0:
            self.on_menu(3)
        elif mint == 1:
            self.on_menu(3)
            QCoreApplication.postEvent(self, QCloseEvent())
        elif mint == QSystemTrayIcon.Trigger:
            #PyCWnd = win32ui.FindWindowEx(None,None,"Qt5152QWindowIcon","主页面")
            self.showNormal()
            self.raise_()
            #win32gui.SetForegroundWindow(PyCWnd.GetSafeHwnd())
        elif mint == 4:
            self.on_menu(3) 

    def on_pushButton(self,mint):
        if not hasattr(self, mint.__name__):
            setattr(self, mint.__name__, mint(self))
        mclass = getattr(self, mint.__name__)  
        mclass.show()
        mclass.showNormal()
        mclass.raise_()



class Configui_Gui(QWidget, configui.Ui_Form):
    def __init__(self,windwos):
        super(Configui_Gui, self).__init__()
        self.windwos = windwos
        self.setupUi(self)
        self.label_4.setMinimumSize(QSize(70, 30))
        self.label_4.setMaximumSize(QSize(16777215, 30))
        self.label_4.setFrameShape(QFrame.NoFrame)
        self.label_4.setLineWidth(0)
        self.spinBox.setMinimumSize(QSize(70, 0))

        self.comboBox.setCurrentIndex(config.Myconfig._cargo)
        self.comboBox_2.setCurrentIndex(config.Myconfig._write)
        self.comboBox_3.setCurrentIndex(config.Myconfig._theme)
        self.label_4.setAlignment(Qt.AlignCenter)
        self.checkBox.setCheckState(config.Myconfig._state)
        self.checkBox_2.setCheckState(config.Myconfig._synch)
        self.spinBox.setValue(config.Myconfig._mdays)
        self.lineEdit.setText(config.Myconfig._mhttp)
        self.comboBox.currentIndexChanged.connect(lambda : self.on_comboBox(0))
        self.comboBox_2.currentIndexChanged.connect(lambda : self.on_comboBox(1))
        self.comboBox_3.currentIndexChanged.connect(lambda : self.on_comboBox(2))
        self.checkBox_2.stateChanged.connect(lambda : self.on_comboBox(3))
        self.checkBox.stateChanged.connect(lambda : self.on_comboBox(4))
        self.spinBox.valueChanged.connect(lambda : self.on_comboBox(5))
        self.pushButton.clicked.connect(lambda : self.on_comboBox(6))
        self.setWindowTitle('设置')
        self.setCursor(QCursor(self.windwos.icon))

        self.windwos.qthead.Dic_Signal.connect(self.mevent)
        self.code = 102

    def mevent(self,dic):
        if self.code == dic['code']:
            print(dic)
            if dic['mode'] == 'close':
                self.pushButton.setEnabled(True)
                self.pushButton.setText("检查更新")

            elif dic['mode'] == 'err':
                self.pushButton.setEnabled(True)
                self.pushButton.setText("检查更新")
                mparts.My_QMessageBox("错误", dic['ret'], self).exec_()

            elif dic['mode'] == 'update':
                self.pushButton.setText(str(dic['ret']) + "%")

            elif dic['mode'] == 'vers':
                mparts.My_QMessageBox("错误", "没有新版本可更新", self).exec_()
            
    def closeEvent(self, event):
        self.windwos.myclose(type(self).__name__,self.mevent)

    def on_comboBox(self,mint):
        if mint == 0:
            config.Myconfig.setcargo(self.comboBox.currentIndex())
        elif mint == 1:
            config.Myconfig.setwrite(self.comboBox_2.currentIndex())
        elif mint == 2:
            config.Myconfig.settheme(self.comboBox_3.currentIndex())
            Palette = qdarkstyle.palette.Palette()
            qpxmp = QPixmap()
            qpxmp.loadFromData(image.img[self.comboBox_3.currentIndex()])
            if self.comboBox_3.currentIndex() == 0:
                Palette.ID = "dark"
            else:
                Palette.ID = "light"
            self.windwos.icon = qpxmp
            self.windwos.setCursor(QCursor(self.windwos.icon))
            self.setCursor(QCursor(self.windwos.icon))
            self.windwos.qthead.my_call(mydef.update_icon)
            app.setStyleSheet(qdarkstyle._load_stylesheet(qt_api='pyqt5', palette=Palette))
        elif mint == 3:
            config.Myconfig.setsynch(self.checkBox_2.checkState())
        elif mint == 4:
            config.Myconfig.setstate(self.checkBox.checkState())
            if self.checkBox.checkState():
                mydef.addfile2autorun(os.path.abspath(sys.argv[0]),True)
            else:
                mydef.addfile2autorun(os.path.abspath(sys.argv[0]),False)
        elif mint == 5:
            config.Myconfig.setmdays(self.spinBox.value())
        elif mint == 6:
            ulr_ip = self.lineEdit.text()            
            config.Myconfig.setmhttp(ulr_ip)
            self.pushButton.setEnabled(False)
            self.pushButton.setText("检查中")
            self.windwos.qthead.my_call(mydef.myupdate, ulr_ip, config.Myconfig._mid)
            #os.startfile(sys.executable)



if __name__ == '__main__':
    app = mparts.QSingleApplication(sys.argv)
    if app.isRunning():
        app.sendMessage(time.strftime("%Y-%m-%d %H:%M:%S"))
        sys.exit(0)
    win = Mainui_Gui()
    win.show()
    app.messageReceived.connect(win.isrung)
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    # or in new API
    Palette = qdarkstyle.palette.Palette()
    if config.Myconfig._theme == 0:
        Palette.ID = "dark"
    else:
        Palette.ID = "light"
    app.setStyleSheet(qdarkstyle._load_stylesheet(qt_api='pyqt5', palette=Palette))
    sys.exit(app.exec_())


